var localVideo = document.querySelector("video#localVideoId")
var remoteVideo = document.querySelector("video#remoteVideoId")

var startBtn = document.querySelector('button#start')
var callBtn = document.querySelector('button#call')
var hangupBtn = document.querySelector('button#hangup')

var localStream = null
var pc1 = null
var pc2 = null

function getMediaStream(stream) {
    localStream = stream
    localVideo.srcObject = stream
}

function handleMediaStreamError(e) {
    console.log(e)
}

startBtn.onclick = () => {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
       console.log('the getUserMedia is not supported!')
       return
    } else {
        const constraints = {
            video: true,
            audio: true,
        }
        navigator.mediaDevices.getUserMedia(constraints).then(getMediaStream).catch(handleMediaStreamError)
    }
}

function getRemoteStream(e) {
    remoteVideo.srcObject = e.streams[0]
}

const handleOfferError = err => {
    console.error('Failed to create offer:',err)
}

const handleAnswerError = err => {
    console.error('Failed to create answer:',err)
}

function getOffer(desc) {
    pc1.setLocalDescription(desc)

    //send desc to signal
    //receive desc from signal
    pc2.setRemoteDescription(desc)
    pc2.createAnswer().then(getAnswer).catch(handleAnswerError)
}

function getAnswer(desc) {
    pc2.setLocalDescription(desc)

    //send desc to signal
    //receive desc to signal
    pc1.setRemoteDescription(desc)
} 

callBtn.onclick = () => {
    pc1 = new RTCPeerConnection()
    pc2 = new RTCPeerConnection()

    pc1.onicecandidate = e => {
        pc2.addIceCandidate(e.candidate)
    }

    pc2.onicecandidate = e => {
        pc1.addIceCandidate(e.candidate)
    }

    pc2.ontrack = getRemoteStream

    localStream.getTracks().forEach(track => {
        pc1.addTrack(track,localStream)
    })

    var offerOptions = {
        offerToRecieveAudio: 1,
        offerToRecieveVideo: 1
    }
    pc1.createOffer(offerOptions).then(getOffer).catch(handleOfferError)
}

hangupBtn.onclick = () => {
    pc1.close()
    pc2.close()
    pc1 = null
    pc2 = null
}